package com.sayimo.maker.commons.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Servlet Filter implementation class JSONFilter
 */
public class JSONFilter implements Filter {

	private static Log logger = LogFactory.getLog(JSONFilter.class);

	/**
	 * Default constructor.
	 */
	public JSONFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		WrapperedResponse wrapResponse = new WrapperedResponse((HttpServletResponse) response);
		wrapResponse.setCharacterEncoding("UTF-8");
		wrapResponse.setContentType("text/html; charset=UTF-8");
		// wrapResponse.addHeader("Access-Control-Allow-Origin", "*");
		chain.doFilter(request, wrapResponse);
		
		
		byte[] data = wrapResponse.getResponseData();
		String result = new String(data, Charset.forName("UTF-8"));
		logger.info("result = " + result);
		HttpServletResponse httpServletResponse = (HttpServletResponse) wrapResponse.getResponse();
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("text/html; charset=UTF-8");
		// httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
		String allowOrigin = httpServletResponse.getHeader("Access-Control-Allow-Origin");
		logger.info(allowOrigin);
		if (StringUtils.isEmpty(allowOrigin)) {
			httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
			httpServletResponse.addHeader("Access-Control-Allow-Headers", "sayimotoken,Cache-Control");
		}
		
		PrintWriter printWriter = httpServletResponse.getWriter();
		printWriter.write(result);
		IOUtils.closeQuietly(printWriter);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}
	
}
